import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_demo/controllers/article_search_controller.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:get/get.dart';

import '../entities/article_item.dart';
import '../utils/const.dart';
import '../views/loading_container.dart';
import 'article_detail_page.dart';

class ArticleSearchPage extends GetView<ArticleSearchController> {
  const ArticleSearchPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Get.put(ArticleSearchController());
    return Scaffold(
      appBar: AppBar(
        titleSpacing: 0,
        title: Obx(
          () => TextField(
            focusNode: controller.searchFocus,
            onSubmitted: _handleSearch,
            controller: TextEditingController.fromValue(
              TextEditingValue(
                text: controller.searchKey.value,
                selection: TextSelection.fromPosition(
                  TextPosition(affinity: TextAffinity.downstream, offset: controller.searchKey.value.length),
                ),
              ),
            ),
            autofocus: true,
            textInputAction: TextInputAction.search,
            decoration: InputDecoration(
                suffix: GestureDetector(
                  child: Icon(
                    Icons.clear_outlined,
                    color: Get.theme.primaryColorDark,
                    size: 18,
                  ),
                  onTap: () {
                    controller.search("");
                  },
                ),
                contentPadding: const EdgeInsets.fromLTRB(12, 6, 12, 6),
                isCollapsed: true,
                fillColor: Get.theme.secondaryHeaderColor,
                filled: true,
                border: OutlineInputBorder(borderRadius: BorderRadius.circular(40))),
          ),
        ).paddingOnly(right: 13),
        elevation: 0,
        toolbarHeight: Const.kAppBarHeight,
      ),
      body: Obx(() => controller.type.value == "history" ? _buildHistoryContent() : _buildSearchContent()),
    );
  }

  Widget _buildHistoryContent() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Container(
              color: Get.theme.primaryColor,
              width: 3,
              height: 15,
            ).paddingOnly(right: 5),
            const Text(
              "历史",
              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
            )
          ],
        ).paddingOnly(bottom: 10),
        Wrap(
          alignment: WrapAlignment.start,
          children: controller.historyList.val.map((e) => _buildTag(e, editable: true)).toList(),
        ).paddingOnly(bottom: 20),
        Row(
          children: [
            Container(
              color: Get.theme.primaryColor,
              width: 3,
              height: 15,
            ).paddingOnly(right: 5),
            const Text(
              "热门",
              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
            )
          ],
        ).paddingOnly(bottom: 10),
        Wrap(
          alignment: WrapAlignment.start,
          children: ["塞尔达", "龙珠", "马里奥", "暗黑破坏神", "宝可梦", "星之卡比", "博德之门"].map((e) => _buildTag(e)).toList(),
        )
      ],
    ).paddingAll(10);
  }

  Widget _buildSearchContent() {
    return Obx(
      () => LoadingContainer(
        status: controller.listLoadingStatus.value,
        onReload: () => controller.getList(),
        child: EasyRefresh(
          header: PhoenixHeader(),
          onRefresh: () => controller.getList(),
          onLoad: controller.hasMore.value ? () => controller.getList(init: false) : null,
          child: GridView.builder(
              itemCount: controller.list.length,
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, childAspectRatio: 1.04),
              itemBuilder: (BuildContext context, int index) {
                return _buildArticleItem(controller.list[index], index);
              }),
        ),
      ),
    );
  }

  Widget _buildTag(String text, {editable = false}) {
    return InkWell(
      onTap: () => controller.search(text),
      onLongPress: () {
        if (editable) {
          controller.clearText.value = text;
        }
      },
      child: Stack(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(3),
            child: Container(
              color: Get.theme.highlightColor,
              padding: const EdgeInsets.fromLTRB(6, 3, 6, 3),
              child: Text(
                text,
                style: Get.theme.textTheme.bodySmall,
              ),
            ),
          ).marginAll(5),
          editable && controller.clearText.value == text
              ? Positioned(
                  child: GestureDetector(
                    onTap: () {
                      controller.removeSearchHistory();
                    },
                    child: ClipOval(
                      child: Container(
                        color: Colors.grey,
                        child: const Icon(
                          Icons.close_rounded,
                          size: 12,
                          color: Colors.white70,
                        ),
                      ),
                    ),
                  ),
                  right: 2,
                  top: 2,
                )
              : const SizedBox(width: 0, height: 0)
        ],
      ),
    );
  }

  _handleToAbout(ArticleItem item) {
    Get.to(() => ArticleDetailPage(), arguments: item);
  }

  Widget _buildArticleItem(ArticleItem item, int index) {
    final isLeft = index % 2 == 0;
    return InkWell(
      onTap: () => _handleToAbout(item),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          AspectRatio(
            aspectRatio: 208 / 117,
            child: CachedNetworkImage(
              imageUrl: item.cover.toString(),
              httpHeaders: Const.imgHeaders,
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(5),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: item.tags
                  .map(
                    (e) => Text(
                      e,
                      style: const TextStyle(fontSize: 12),
                      overflow: TextOverflow.clip,
                    ),
                  )
                  .toList(),
            ),
          ),
          Text(
            item.title.toString(),
            style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
            maxLines: 2,
          )
        ],
      ).paddingOnly(left: isLeft ? 5 : 4, top: 5, right: isLeft ? 4 : 5, bottom: 5),
    );
  }

  _handleSearch(String value) {
    controller.setType("search");
    controller.search(value);
  }
}
